﻿Imports Persistencia

Public Class frmUsuario

#Region "Declaração de variáveis"
    Private objUsuario As New Controle.ctrUsuario
    Private objUsuariosSetores As New Controle.ctrUsuariosSetores
    Private objSetor As New Controle.ctrSetores
    Private objSeguranca As New perSeguranca
    Private iIdUsuario As Int32
    Private sMensagemValidacao As String = ""
    Private dtSetores As DataTable
    Private dtUsuariosSetores As DataTable
#End Region

#Region "Propriedades"

    Public Property IDUsuario() As Int32
        Get
            Return Me.iIdUsuario
        End Get
        Set(ByVal value As Int32)
            Me.iIdUsuario = value
        End Set
    End Property

#End Region

#Region "Métodos"

    Private Enum eColSetores
        eIdSetor = 0
        eNomeNome = 1
        eMarcar = 2
    End Enum

    Private Sub FormataDtGrid()

        Dim Colunas As New DataGridViewTextBoxColumn()
        Dim dsDados As New DataSet

        Try
            With Me.dtGridSetores

                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .AutoGenerateColumns = False
                .RowHeadersVisible = False
                .Columns.Clear()

                Dim Col As New DataGridViewTextBoxColumn()
                Col.HeaderText = "IDSetor"
                Col.Width = 15
                Col.Frozen = True
                Col.ReadOnly = True
                Col.FillWeight = 100
                Col.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet
                Col.SortMode = DataGridViewColumnSortMode.Automatic
                Col.Visible = False
                Col.ValueType = System.Type.GetType("String")
                .Columns.Add(Col)

                Dim Col1 As New DataGridViewTextBoxColumn()
                Col1.HeaderText = "Setores"
                Col1.Width = 240
                Col1.Frozen = True
                Col1.ReadOnly = True
                Col1.FillWeight = 100
                Col1.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet
                Col1.SortMode = DataGridViewColumnSortMode.Automatic
                Col1.Visible = True
                Col1.ValueType = System.Type.GetType("String")
                .Columns.Add(Col1)

                Dim Col2 As New DataGridViewCheckBoxColumn
                Col2.HeaderText = "Marcar"
                Col2.Width = 70
                Col2.Frozen = True
                Col2.ReadOnly = False
                Col2.FillWeight = 100
                Col2.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet
                Col2.SortMode = DataGridViewColumnSortMode.NotSortable
                Col2.Visible = True
                Col2.ValueType = System.Type.GetType("Boolean")
                .Columns.Add(Col2)

                .Refresh()

            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try

    End Sub

    Private Sub PreencherDtGrid()

        Try
            Me.dtSetores = Me.objSetor.selecionarSetor(0)
            Me.dtUsuariosSetores = Me.objUsuariosSetores.selecionarUsuarioSetor(0, perConversao.ToInt32(Me.txtIdUsuario.Text))

            If Not Me.dtSetores Is Nothing AndAlso Me.dtSetores.Rows.Count > 0 Then
                With Me.dtSetores
                    If (.Rows.Count > 0) Then

                        dtGridSetores.Rows.Clear()
                        dtGridSetores.RowCount = .Rows.Count

                        For cont As Integer = 0 To .Rows.Count - 1
                            Me.dtGridSetores.Item(eColSetores.eIdSetor, cont).Value = .Rows(cont).Item("IDSetor").ToString
                            Me.dtGridSetores.Item(eColSetores.eNomeNome, cont).Value = .Rows(cont).Item("Setor").ToString
                            Me.dtGridSetores.Item(eColSetores.eMarcar, cont).Value = False
                        Next

                    End If
                End With
            End If

            If Not Me.dtUsuariosSetores Is Nothing AndAlso Me.dtUsuariosSetores.Rows.Count > 0 Then
                With Me.dtUsuariosSetores
                    If (.Rows.Count > 0) Then
                        dtGridSetores.RowCount = .Rows.Count
                        For cont As Integer = 0 To .Rows.Count - 1
                            If Me.dtGridSetores.Item(eColSetores.eIdSetor, cont).Value = Persistencia.perConversao.ToInt32(.Rows(cont).Item("IDSetor")) Then
                                Me.dtGridSetores.Item(eColSetores.eMarcar, cont).Value = True
                            End If
                        Next
                    End If
                End With
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try
    End Sub

    Private Sub frmEstado_alteraModo(ByVal eModoAtual As frmPadrao.eModo) Handles Me.alteraModo
        If (eModoAtual = eModo.eAguardar Or eModoAtual = eModo.eExcluir) Then
            Me.lblNome.Enabled = False
            Me.txtNome.Enabled = False
            Me.lblGrupoAcesso.Enabled = False
            Me.txtIdGrupoAcesso.Enabled = False
            Me.txtGrupoAcesso.Enabled = False
            Me.cmdProcuraGrupoAcesso.Enabled = False
            Me.lblLogin.Enabled = False
            Me.txtLogin.Enabled = False
            Me.lblSenha.Enabled = False
            Me.txtSenha.Enabled = False
            Me.lblCodigo.Enabled = True
            Me.txtIdUsuario.Enabled = True
            Me.cmdProcura.Enabled = True
            Me.dtGridSetores.Enabled = False
        Else
            Me.lblNome.Enabled = True
            Me.txtNome.Enabled = True
            Me.lblGrupoAcesso.Enabled = True
            Me.txtIdGrupoAcesso.Enabled = True
            Me.txtGrupoAcesso.Enabled = True
            Me.cmdProcuraGrupoAcesso.Enabled = True
            Me.lblLogin.Enabled = True
            Me.txtLogin.Enabled = True
            Me.lblSenha.Enabled = True
            Me.txtSenha.Enabled = True
            Me.lblCodigo.Enabled = False
            Me.txtIdUsuario.Enabled = False
            Me.cmdProcura.Enabled = False
            Me.dtGridSetores.Enabled = True
        End If
    End Sub

    Private Sub frmUsuario_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.txtIdUsuario.Focus()
        Me.FormataDtGrid()
        Me.PreencherDtGrid()
        modoAtual = eModo.eAguardar
    End Sub

    Private Sub cmdGravar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGravar.Click
        Dim bRetorno As Boolean
        Dim dsSetores As New DataSet

        Try

            dsSetores = MyBase.converteGridParaDataset(Me.dtGridSetores, "DC_UsuariosSetores")

            If Me.validarFormulario Then
                bRetorno = Me.objUsuario.salvar(Me.IDUsuario, _
                                                Me.txtNome.Text, _
                                                Me.txtLogin.Text, _
                                                Me.txtSenha.Text, _
                                                perConversao.ToInt32(Me.txtIdGrupoAcesso.Text), _
                                                dsSetores)

                If bRetorno Then
                    Me.IDUsuario = Me.objUsuario.IDUsuario
                    MyBase.Codigo = Me.IDUsuario
                    MyBase.modoAtual = eModo.eAguardar
                    Me.txtIdUsuario.Text = Me.IDUsuario
                End If
            Else
                MsgBox(Me.sMensagemValidacao, MsgBoxStyle.Exclamation, Me.Text)
                Me.cmdCancelar.Text = "Cancelar"
                MyBase.modoAtual = eModo.eEditar
                Exit Sub
            End If

        Catch ex As Exception
            Me.Limpar(Me)
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try
    End Sub

    Private Sub cmdExcluir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExcluir.Click
        Try
            If MyBase.Exclui Then
                If Me.objUsuario.excluir(Me.txtIdUsuario.Text) Then
                    MyBase.Codigo = 0
                    MyBase.Limpar(Me)
                    MyBase.modoAtual = eModo.eAguardar
                    Me.txtIdUsuario.Focus()
                Else
                    MsgBox("Exclusão cancelada. Existem registros vinculados", MsgBoxStyle.Exclamation, Me.Text)
                    MyBase.modoAtual = eModo.eAguardar
                    Exit Sub
                End If

            End If
        Catch ex As Exception
            MyBase.Codigo = 0
            Me.IDUsuario = 0
            MyBase.modoAtual = eModo.eAguardar
            Me.Limpar(Me)
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try
    End Sub

    Private Sub cmdNovo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNovo.Click
        Me.txtNome.Focus()
        Me.IDUsuario = MyBase.Codigo
    End Sub

    Private Sub cmdCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancelar.Click
        If Me.cmdCancelar.Text = "Alterar" Then
            Me.txtIdUsuario.Focus()
        Else
            Me.txtNome.Focus()
        End If
    End Sub

    Private Function validarFormulario() As Boolean

        Dim bRetorno As Boolean = True
        sMensagemValidacao = ""

        If Me.txtNome.Text = String.Empty Then
            sMensagemValidacao = "- Nome obrigatório."
            bRetorno = False
        End If

        If Me.txtLogin.Text = String.Empty Then
            sMensagemValidacao = "- Login obrigatório."
            bRetorno = False
        End If

        If Me.txtSenha.Text = String.Empty Then
            sMensagemValidacao = "- Senha obrigatória."
            bRetorno = False
        End If

        'If Me.txtIdGrupoAcesso.Text = String.Empty Then
        '    sMensagemValidacao &= Environment.NewLine & "- Grupo de acesso obrigatório."
        '    bRetorno = False
        'End If

        Return bRetorno

    End Function

    Private Sub carregaDados()
        Dim drDados As DataRow

        Try
            If Me.IDUsuario > 0 Then
                drDados = Me.objUsuario.selecionarUsuario(Me.IDUsuario)
                Me.txtNome.Text = drDados.Item("Nome")
                Me.txtLogin.Text = Me.objUsuario.desencriptarSenha(drDados.Item("Login"))
                Me.txtSenha.Text = drDados.Item("Senha")
                Me.txtIdGrupoAcesso.Text = drDados.Item("IDGrupoAcesso")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try

    End Sub

    Private Sub txtIDUsuario_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtIdUsuario.LostFocus
        Dim drDados As DataRow

        Try
            If Me.txtIdUsuario.Text <> String.Empty Then
                drDados = Me.objUsuario.selecionarUsuario(Convert.ToInt32(Me.txtIdUsuario.Text))
                If Not drDados Is Nothing Then
                    Me.txtNome.Text = perConversao.ToString(drDados.Item("Nome"))
                    Me.txtLogin.Text = Me.objUsuario.desencriptarSenha(drDados.Item("Login"))
                    Me.txtSenha.Text = drDados.Item("Senha")
                    Me.txtIdGrupoAcesso.Text = drDados.Item("IDGrupoAcesso")
                    MyBase.Codigo = drDados.Item("IDUsuario")
                    Me.IDUsuario = MyBase.Codigo
                    MyBase.modoAtual = eModo.eAguardar
                Else
                    MsgBox("Registro não encontrado", MsgBoxStyle.Exclamation, Me.Text)
                    Exit Sub
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try

    End Sub

    Private Sub cmdProcura_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdProcura.Click
        Dim sql As String
        Dim frmDialogo As New frmPesquisa

        sql = Me.objUsuario.sqlConsulta

        With frmDialogo
            .Campos = "iIDUsuario,sNome"
            .Descricoes = "Código,Nome"
            .Larguras = "50,300"
            .Sql = sql
            .Titulo = "Pesquisa de usuários"
            .CarregaTela()
            If .DS.Tables(0).Rows.Count > 0 Then
                .ShowDialog()
                If (.DialogResult = Windows.Forms.DialogResult.OK) Then
                    MyBase.Codigo = .Id
                    Me.IDUsuario = MyBase.Codigo
                    Me.txtIdUsuario.Text = Me.IDUsuario
                    Me.carregaDados()
                    Me.modoAtual = eModo.eAguardar
                End If
            Else
                MsgBox("Registro não encontrado", MsgBoxStyle.Exclamation, Me.Text)
                Exit Sub
            End If

        End With
    End Sub

    'Private Sub txtIdGrupoAcesso_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtIdGrupoAcesso.LostFocus

    '    Try
    '        If Me.txtIdGrupoAcesso.Text <> String.Empty Then
    '            Me.preencheDescricaoGrupoAcesso(Me.txtIdGrupoAcesso.Text)
    '        Else
    '            Me.txtGrupoAcesso.Text = String.Empty
    '        End If
    '    Catch ex As Exception
    '        MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
    '    End Try

    'End Sub

    'Private Sub cmdProcuraGrupoAcesso_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdProcuraGrupoAcesso.Click
    '    Dim sql As String
    '    Dim frmDialogo As New frmPesquisa

    '    sql = Me.objGrupoAcesso.sqlConsulta

    '    With frmDialogo
    '        .Campos = "IDGrupoAcesso,GrupoAcesso"
    '        .Descricoes = "Código,Nome"
    '        .Larguras = "50,300"
    '        .Sql = sql
    '        .Titulo = "Pesquisa de Grupos de Acesso"
    '        .CarregaTela()
    '        If .DS.Tables(0).Rows.Count > 0 Then
    '            .ShowDialog()
    '            If (.DialogResult = Windows.Forms.DialogResult.OK) Then
    '                Me.preencheDescricaoGrupoAcesso(.Id)
    '            End If
    '        Else
    '            MsgBox("Registro não encontrado", MsgBoxStyle.Exclamation, Me.Text)
    '            Exit Sub
    '        End If
    '    End With
    'End Sub

    'Private Sub preencheDescricaoGrupoAcesso(ByVal iIdGrupoAcesso As Int32)

    '    Dim drDados As DataRow

    '    drDados = Me.objGrupoAcesso.selecionarGrupoAcesso(iIdGrupoAcesso)
    '    If Not drDados Is Nothing Then
    '        Me.txtGrupoAcesso.Text = drDados.Item("GrupoAcesso")
    '        Me.txtIdGrupoAcesso.Text = drDados.Item("IDGrupoAcesso")
    '    Else
    '        MsgBox("Registro não encontrado", MsgBoxStyle.Exclamation, Me.Text)
    '        Me.txtIdGrupoAcesso.Text = String.Empty
    '        Me.txtIdGrupoAcesso.Focus()
    '        Exit Sub
    '    End If

    'End Sub

#End Region

    Private Sub dtGridSetores_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dtGridSetores.CellClick
        If (e.ColumnIndex = eColSetores.eMarcar) Then
            With dtGridSetores
                .Item(eColSetores.eMarcar, e.RowIndex).Value = Not (.Item(eColSetores.eMarcar, e.RowIndex).Value)
            End With
        End If
    End Sub

End Class
